<template>
  <div id="area-box">
    <div id="area-content">
      <w-panel-fixed-wrap v-model="show" class="cb pop" title="选择区域" width="600px" height="500px" @on-confirm="saveAreaList" @on-cancel="dismissAreaBox">
        <div class="line" v-for="(area, index) in datas" :key="index">
          <div class="col-sm-3 pd5">
            <w-checkbox 
              @on-change="selectChildrenArea(area)" 
              :label="area.id" 
              v-model="area.isSelected">
              {{area.areaName}}
            </w-checkbox>
          </div>
          <div class="col-sm-9">
            <div class="col-sm-4 pd5" v-for="(province, pIndex) in area.childs" :key="pIndex">
              <w-checkbox 
                :label="province.id" 
                v-model="province.isSelected"
                @on-change="changeProvinceState(province)">
                {{province.areaName}}
              </w-checkbox>
              <span class="dropdown transition" :class="{on: province.showChild}" @click="showCityChild(province)"></span>
              <div class="city-container" v-show="province.showChild">
                <div class="col-sm-12 tr"><span class="close" @click="hiddenCityChild(province)">关闭</span></div>
                <div class="col-sm-6 pd5" v-for="(citys, cIndex) in province.childs" :key="cIndex">
                  <w-checkbox 
                    :label="citys.id" 
                    v-model="citys.isSelected"
                    @on-change="changeProvinceState(citys)">
                    {{citys.areaName}} 
                  </w-checkbox>
                </div>
              </div>
            </div>
          </div>
          <div class="clear"></div>
        </div>
      </w-panel-fixed-wrap>
    </div>
    <!-- <div id="shade"></div> -->
  </div>
</template>

<script>
// 导入物流地址
import { apiDeliveryMange } from 'js/api'
// 导入缓存接口
import { session } from 'js/util'

export default {
  data() {
    return {
      datas: [],
      show: false,
      areaArr: []
    }
  },
  watch: {
    toast() {
      this.show = this.toast
    }
  },
  props: {
    toast: {
      type: Boolean,
      default: false
    }
  },
  created() {
    this.show = this.toast
    // 获取地区列表
    let areaList = session.get('area-list')

    // 如果从缓存中获取到值，则不再从接口中获取值
    if (areaList && areaList.length > 0) {
      this.datas = areaList
    }

    // 从接口获取数据
    apiDeliveryMange.apiGetAreaAll().then((data) => {
      this.datas = data.data.transArea
      // 遍历数据，将大区域数据（华东，华北等）返回
      this.datas.forEach((v) => {
        // 设置全部的省市区域都未选中
        this.$set(v, 'isSelected', false)

        // 将地区下面的所有组件设置为未选中状态
        v.childs.forEach((v1) => {
          this.$set(v1, 'isSelected', false)
          this.$set(v1, 'showChild', false)
        })
      })

      // 将数据保存造缓存中
      session.set('area-list', this.datas)
    })
  },
  methods: {
    /**
     * 获取点击的大区域下的省市
     * 如：我点击了华东（大区域），则将华东下面的省全部选中
     *
     * @param {Object} area 当前的大区域
     * @return {[type]} [description]
     */
    selectChildrenArea(area) {
      this.areaArr = [] // 重置数据
      area.childs.forEach((v) => {
        v.isSelected = area.isSelected
        if (v.isSelected) {
          this.areaArr.push({id: v.id, name: v.areaName})
        }
      })
    },

    /**
     * 改变当前省的选中状态
     * @param  { Object } province [description]
     */
    changeProvinceState(province) {
      // 如果当前是选中状态
      if (province.isSelected) {
        this.areaArr.push({id: province.id, name: province.areaName})
        return
      }

      // 如果当前没有选中任何省市
      if (!this.areaArr || this.areaArr.length == 0) {
        return
      }

      // 将未选中的省从数据中拿出来
      this.areaArr = this.areaArr.filter((v) => {
        return v.id != province.id
      })
    },

    /**
     * 展示省下面的市
     *
     * @param {Object} province 当前的省
     */
    showCityChild(province) {
      // 打开弹框
      province.showChild = !province.showChild

      // 如果从未请求过接口，则开始加载数据
      if (!province.childs) {
        // 请求下级数据
        apiDeliveryMange.apiGetCity(province.id).then((data) => {
          this.$set(province, 'areaList', data.data.city)

          // 遍历接口数据
          province.childs.forEach((v) => {
            this.$set(v, 'isSelected', province.isSelected)
          })
        })
      }
    },

    /**
     * 隐藏省下面的市
     *
     * @param  {Object} province 当前省
     */
    hiddenCityChild(province) {
      province.showChild = false
    },

    /**
     * 销毁组件
     *
     * @return {[type]} [description]
     */
    dismissAreaBox() {
      this.$emit('close')
    },

    /**
     * 保存地址信息
     */
    saveAreaList() {
      // 市id集合
      let cityIds = []
      let index = 0

      // 查询省下面的数据
      this.areaArr.forEach((province) => {
        apiDeliveryMange.apiGetCity(province.id).then((data) => {
          data.data.city.forEach((v1) => {
            cityIds.push({ id: v1.id, name: province.name })
          })

          index++

          // 如果接口请求结束
          if (index == this.areaArr.length) {
            this.$emit('input', cityIds)
            this.$emit('sure', cityIds)
            this.$emit('close')
          }
        })
      })
    }
  }
}
</script>

<style lang="scss" scoped>
#shade {
  background-color: rgba(0, 0, 0, 0.4);
  width: 100%;
  height: 100%;
  position: fixed;
  top: 0px;
  left: 0px;
  z-index: 8;
}

.tc {
  text-align: center;
}

.close {
  cursor: pointer;
  color: #F20685;
}

#area-box {
  width: 600px;
  
  #area-content {
    position: fixed;
    top: 20%;
    left: 40%;
    z-index: 100;
  }

  .line {
    margin-top: 8px;

    .pd5 {
      padding-top: 5px;
      padding-bottom: 5px;
      position: relative;
    }

    .clear {
      clear: both;
    }

    .tr {
      text-align: right;
    }

    .dropdown {
      border-top: 4px solid #666666;
      border-left: 4px solid transparent;
      border-right: 4px solid transparent;
      cursor: pointer;
      display: inline-block;
      margin: 3px 4px;

      &.on {
        transform: rotate(180deg);
      }
    }

    .city-container {
      background-color: #FFFFFF;
      border: 1px solid rgba(102, 102, 102, 0.1);
      box-shadow: 2px 2px 2px -2px rgba(102, 102, 102, 0.6);
      width: 210px;
      padding: 10px;
      right: 0px;
      z-index: 10;

      &.on {
        display: block;
      }
    }

    .city-container {
      position: absolute;
    }
  }
}
</style>